package com.wbao.dianniu.im;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.aop.Pointcut;
import com.alibaba.mobileim.aop.custom.IMConversationListUI;
import com.alibaba.mobileim.contact.IYWContact;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWConversationType;
import com.alibaba.mobileim.conversation.YWP2PConversationBody;
import com.alibaba.mobileim.kit.contact.YWContactHeadLoadHelper;
import com.alibaba.mobileim.lib.presenter.conversation.CustomViewConversation;
import com.alibaba.mobileim.utility.IMSmilyCache;
import com.alibaba.mobileim.utility.IMUtil;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.R;

/**
 * 自定义会话列表
 * 
 * @author yejianjun
 * 
 */
public class MyConversationUI extends IMConversationListUI {
	public MyConversationUI(Pointcut pointcut) {
		super(pointcut);
	}

	/**
	 * 返回会话列表的自定义标题
	 * 
	 * @param fragment
	 * @param context
	 * @param inflater
	 * @return
	 */
	@Override
	public View getCustomConversationListTitle(final Fragment fragment,
			final Context context, LayoutInflater inflater) {
		// TODO 重要：必须以该形式初始化customView---［inflate(R.layout.**, new
		// RelativeLayout(context),false)］------，以让inflater知道父布局的类型，否则布局xml**中定义的高度和宽度无效，均被默认的wrap_content替代
		RelativeLayout customView = (RelativeLayout) inflater.inflate(R.layout.include_title, new RelativeLayout(context), false);
		TextView title = (TextView) customView.findViewById(R.id.title);
		title.setText("消息");

		// 通讯录
		ImageButton bookButton = (ImageButton) customView.findViewById(R.id.back_button);
		bookButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 通讯录列表
				Intent intent = new Intent();
				intent.setClass(context, ConversationBook2.class);
				context.startActivity(intent);
			}
		});
		bookButton.setImageResource(R.drawable.msg_book_icon);
		bookButton.setVisibility(View.VISIBLE);
		// 加好友
		ImageButton addButton = (ImageButton) customView.findViewById(R.id.right_imagebutton);
		addButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// 加好友列表
				Intent intent = new Intent();
				intent.setClass(context, AddFriendActivity.class);
				context.startActivity(intent);
			}
		});
		addButton.setImageResource(R.drawable.add_icon);
		addButton.setVisibility(View.VISIBLE);
		return customView;
	}

	@Override
	public boolean needHideTitleView(Fragment fragment) {
		return false;
	}

	@Override
	public boolean needHideNullNetWarn(Fragment fragment) {
		return false;
	}

	/**
	 * 是否支持下拉刷新
	 */
	@Override
	public boolean getPullToRefreshEnabled() {
		return true;
	}

	/**
	 * 返回默认的群头像
	 * 
	 * @param fragment
	 * @param conversation
	 * @return
	 */
	@Override
	public int getTribeConversationHead(Fragment fragment,YWConversation conversation) {
		return R.drawable.default_head_icon;
	}

	/**
	 * 返回自定义置顶回话的背景色(16进制字符串形式)
	 * 
	 * @return
	 */
	@Override
	public String getCustomTopConversationColor() {
		return "#e1f5fe";
//		return "#ffe2a4";
	}

	@Override
	public boolean enableSearchConversations(Fragment fragment) {
		return true;
	}

	/**
	 * 获取自定义会话要展示的自定义View，该方法的实现类完全似于BaseAdapter中getView()方法实现
	 * 
	 * @param context
	 * @param conversation
	 *            自定义展示View的会话
	 * @param convertView
	 *            {@link android.widget.BaseAdapter#getView(int, View, ViewGroup)}
	 *            的第二个参数
	 * @param parent
	 *            {@link android.widget.BaseAdapter#getView(int, View, ViewGroup)}
	 *            的第三个参数
	 * @return
	 */
	@Override
	public View getCustomView(Context context, YWConversation conversation,
			View convertView, ViewGroup parent) {
		System.out.println("自定义会话。。。");
		LayoutInflater inflater = LayoutInflater.from(context);
		ViewHolder viewHolder = null;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = inflater.inflate( R.layout.demo_conversation_custom_view_item, parent, false);
			convertView.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}

		viewHolder.conversationName = (TextView) convertView.findViewById(R.id.conversation_name);
		viewHolder.conversationContent = (TextView) convertView.findViewById(R.id.conversation_content);
		CustomViewConversation customViewConversation = (CustomViewConversation) conversation;
		if (TextUtils.isEmpty(customViewConversation.getConversationName())){
			viewHolder.conversationName.setText("可自定义View布局的会话");
		}else
			viewHolder.conversationName.setText(customViewConversation.getConversationName());
		
		viewHolder.conversationContent.setText(customViewConversation.getLatestContent());
		return convertView;
	}

	/**
	 * {@link ConversationListUICustomSample#getCustomView(Context, YWConversation, View, ViewGroup)}
	 * 中使用到的ViewHolder示例
	 */
	static class ViewHolder {
		TextView conversationName;
		TextView conversationContent;
	}

	/**
	 * 会话列表onDestroy事件
	 * 
	 * @param fragment
	 */
	@Override
	public void onDestroy(Fragment fragment) {
		super.onDestroy(fragment);
	}

	/**
	 * 会话列表Activity创建事件
	 * 
	 * @param savedInstanceState
	 * @param fragment
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState, Fragment fragment) {
		super.onActivityCreated(savedInstanceState, fragment);
	}

	/**
	 * 会话列表onResume事件
	 * 
	 * @param fragment
	 */
	@Override
	public void onResume(Fragment fragment) {
		super.onResume(fragment);
	}
//
//	/**
//	 * 该方法可以构造一个会话列表为空时的展示View
//	 * 
//	 * @return empty view
//	 */
//	@Override
//	public View getCustomEmptyViewInConversationUI(Context context) {
//		/** 以下为示例代码，开发者可以按需返回任何view */
//		TextView textView = new TextView(context);
//		textView.setText("暂无消息");
//		textView.setGravity(Gravity.CENTER);
//		textView.setTextSize(17);
//		return textView;
//	}
//
	/**
	 * 返回设置最近联系人界面背景的资源Id,返回0则使用默认值
	 * 
	 * @return 资源Id
	 */
	@Override
	public int getCustomBackgroundResId() {
		return 0;
	}

	/*********** 以下是定制会话item view的示例代码 ***********/
	// 114：电纽小助手 115：招聘小助手，116：活动小助手 117： 好友通知 118：面试通知
	// 自定义item view 种类数
	private final int typeCount = 1;
	 //自定义viewType，viewType必须从0开始，然后依次+1递增，且viewType的个数必须等于typeCount，切记切记！！！
	public static final int type_1 = 0;
	// public static final int type_2 = 1;

	/**
	 * 自定义item view的种类数
	 * 
	 * @return 种类数
	 */
	@Override
	public int getCustomItemViewTypeCount() {
		return typeCount;
	}

	/**
	 * 自定义item的viewType
	 * 
	 * @param conversation
	 * @return
	 */
	@Override
	public int getCustomItemViewType(YWConversation conversation) {
		// todo 若修改 YWConversationType.Tribe为自己type，SDK认为您要在｛@link
		// #getCustomItemView｝中完全自定义，针对群的自定义，如getTribeConversationHead会失效。
		// todo 该原则同样适用于 YWConversationType.P2P等其它内部类型，请知晓！
		if (conversation.getConversationType() == YWConversationType.P2P) {
			return type_1;
		}
		return super.getCustomItemViewType(conversation);
	}

	/**
	 * 根据viewType自定义item的view
	 * 
	 * @param fragment
	 * @param conversation
	 *            当前item对应的会话
	 * @param convertView
	 *            convertView
	 * @param viewType
	 *            当前itemView的viewType
	 * @param headLoadHelper
	 *            加载头像管理器，用户可以使用该管理器设置头像
	 * @param parent
	 *            getView中的ViewGroup参数
	 * @return
	 */
	@Override
	public View getCustomItemView(Fragment fragment,YWConversation conversation, View convertView, int viewType,
			YWContactHeadLoadHelper headLoadHelper, ViewGroup parent) {
		if (viewType == type_1) {
			ViewHolder2 holder = null;
			if (convertView == null) {
				LayoutInflater inflater = LayoutInflater.from(fragment.getActivity());
				holder = new ViewHolder2();
				convertView = inflater.inflate(R.layout.conversation_list_item,parent, false);
				holder.head = (ImageView) convertView.findViewById(R.id.head);
				holder.unread = (TextView) convertView.findViewById(R.id.unread);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.content = (TextView) convertView.findViewById(R.id.content);
				holder.atMsgNotify = (TextView) convertView.findViewById(R.id.at_msg_notify);
				holder.time = (TextView) convertView.findViewById(R.id.time);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder2) convertView.getTag();
			}

			String lastContent = conversation.getLatestContent();
			holder.unread.setVisibility(View.GONE);
			int unreadCount = conversation.getUnreadCount();
			if (unreadCount > 0) {
				holder.unread.setVisibility(View.VISIBLE);
				if (unreadCount > 99) {
					holder.unread.setText("99+");
				} else {
					holder.unread.setText(String.valueOf(unreadCount));
				}
			}
			
			YWIMKit imKit = LoginSampleHelper.getInstance().getIMKit();
			YWP2PConversationBody conversationBody = (YWP2PConversationBody) conversation
					.getConversationBody();
			String name = "";
			String path = null;
			if (!TextUtils.isEmpty(conversationBody.getContact().getShowName())) {
				name = conversationBody.getContact().getShowName();
			} else {
				IYWContact contact = imKit.getContactService()
						.getContactProfileInfo(
								conversationBody.getContact().getUserId(),
								conversationBody.getContact().getAppKey());
				// 生成showName，According to id。
				if (contact != null
						&& !TextUtils.isEmpty(contact.getShowName())) {
					name = contact.getShowName();
				}
				if(contact != null && !TextUtils.isEmpty(contact.getAvatarPath())){
					path = contact.getAvatarPath();
				}
			}
			holder.name.setText(name);
			if (null != path) {
				PictureDownloadUtils.displayHeadNotPrefix(fragment.getActivity(),holder.head, path);
			} else {
				holder.head.setImageResource(R.drawable.default_head_icon);
			}
			
//			YWIMKit imKit = LoginSampleHelper.getInstance().getIMKit();
//			IYWContact ic = IMUtility.getContactProfileInfo(conversation.getLatestEServiceContactId(),LoginSampleHelper.APP_KEY );
//			if (null != ic) {
//				String showName = ic.getShowName();
//				String path = ic.getAvatarPath();
//				if (null != path) {
//					PictureDownloadUtils.displayHeadNotPrefix(fragment.getActivity(),holder.head, path);
//				} else {
//					holder.head.setImageResource(R.drawable.default_head_icon);
//				}
//				holder.name.setText(showName == null ? "" : showName);
//			} else {
//				holder.name.setText(conversation.getLastestMessage().getAuthorUserId());
//				holder.head.setImageResource(R.drawable.default_head_icon);
//			}
			
			holder.atMsgNotify.setVisibility(View.GONE);
			holder.content.setText(lastContent);
			setSmilyContent(fragment.getActivity(), lastContent, holder);
			holder.time.setText(IMUtil.getFormatTime(conversation.getLatestTimeInMillisecond(),
					imKit.getIMCore().getServerTime()));
			return convertView;
		}
		return super.getCustomItemView(fragment, conversation, convertView,viewType, headLoadHelper, parent);
	}

	private Map<String, CharSequence> mSmilyContentCache = new HashMap<String, CharSequence>(); // 表情的本地缓存，加速读取速度用
	IMSmilyCache smilyManager;
	int defaultSmilySize = 0;
	private int contentWidth;

	private void setSmilyContent(Context context, String content,ViewHolder2 holder) {
		initSmilyManager(context);
		if (content == null || holder.content.getPaint() == null) {
			CharSequence charSequence = mSmilyContentCache.get(content);
			if (charSequence != null) {
				holder.content.setText(charSequence);
			} else {
				CharSequence smilySpanStr = smilyManager.getSmilySpan(context,content, defaultSmilySize, false);
				mSmilyContentCache.put(content, smilySpanStr);
				holder.content.setText(smilySpanStr);
			}
		} else {
			CharSequence charSequence = mSmilyContentCache.get(content);
			if (charSequence != null) {
				holder.content.setText(charSequence);
			} else {
				CharSequence text = TextUtils.ellipsize(content,holder.content.getPaint(), contentWidth,holder.content.getEllipsize());
				CharSequence smilySpanStr = smilyManager.getSmilySpan(context,String.valueOf(text), defaultSmilySize, false);
				mSmilyContentCache.put(content, smilySpanStr);
				holder.content.setText(smilySpanStr);
			}
		}
	}

	private void initSmilyManager(Context context) {
		if (smilyManager == null) {
			smilyManager = IMSmilyCache.getInstance();
			defaultSmilySize = (int) context.getResources().getDimension(R.dimen.aliwx_smily_column_width);
			int width = context.getResources().getDisplayMetrics().widthPixels;
			contentWidth = width- context.getResources().getDimensionPixelSize(R.dimen.aliwx_column_up_unit_margin)
					* 2- context.getResources().getDimensionPixelSize(R.dimen.aliwx_common_head_size)
					- context.getResources().getDimensionPixelSize(R.dimen.aliwx_message_content_margin_right);
		}
	}

	public class ViewHolder2 {
		ImageView head;
		TextView unread;
		TextView name;
		TextView content;
		TextView atMsgNotify;
		TextView time;
	}

	/*********** 以上是定制会话item view的示例代码 ***********/
	
}
